package com.mrli.cat.weather.service;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.google.gson.Gson;
import com.mrli.cat.weather.R;
import com.mrli.cat.weather.activity.MainActivity;
import com.mrli.cat.weather.activity.WeatherPreferenceActivity;
import com.mrli.cat.weather.database.WeatherContract;
import com.mrli.cat.weather.model.CurrentWeatherDataBean;
import com.mrli.cat.weather.tools.Constant;
import com.mrli.cat.weather.tools.LunarCalendar;
import com.mrli.cat.weather.tools.Utility;
import com.mrli.cat.weather.view.WeatherAppWidgetProvider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

/**
 * 后台更新天气数据
 */
public class WeatherUpdateService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        buildUpdate();
        return super.onStartCommand(intent, flags, startId);
    }

    private void buildUpdate() {
        //设置城市
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String cityName = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "未知");
        RemoteViews view = new RemoteViews(getPackageName(), R.layout.appwidget_layout);
        view.setTextViewText(R.id.list_item_location, cityName);
        //获取数据
        new FetchCurrentWeather(view, getApplicationContext()).execute();
    }

    class FetchCurrentWeather extends AsyncTask<Void, Void, Void> {
        private Context mContext;
        private RemoteViews mRemoteViews;

        public FetchCurrentWeather(RemoteViews remoteViews, Context context) {
            this.mRemoteViews = remoteViews;
            this.mContext = context;
        }

        @Override
        protected Void doInBackground(Void... params) {
            //获取当前的城市位置并构造Uri
            Cursor cursor = getDetailCityInfo();
            if (cursor.moveToFirst()) {
                Uri uri = new Uri.Builder()
                        .appendPath("data")
                        .appendPath("2.5")
                        .appendPath("weather")
                        .appendQueryParameter("lat", String.valueOf(cursor.getDouble(cursor.getColumnIndex(WeatherContract.LocationEntry.COLUMN_LAT))))
                        .appendQueryParameter("lon", String.valueOf(cursor.getDouble(cursor.getColumnIndex(WeatherContract.LocationEntry.COLUMN_LON))))
                        .appendQueryParameter(Constant.OpenWeatherMap.QUERY_UNITS, Constant.OpenWeatherMap.UNITS)
                        .appendQueryParameter(Constant.OpenWeatherMap.QUERY_CODE, Constant.OpenWeatherMap.CODE)
                        .build();
                //建立链接
                BufferedReader readers = null;
                CurrentWeatherDataBean currentWeatherDataBean = null;
                try {
                    URL url = new URL(Constant.OpenWeatherMap.AUTHORITY + uri.toString());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    InputStreamReader reader = new InputStreamReader(inputStream);
                    readers = new BufferedReader(reader);
                    StringBuffer buffer = new StringBuffer();
                    String lines = null;
                    while ((lines = readers.readLine()) != null) {
                        buffer.append(lines + "\n");
                    }
                    Gson gson = new Gson();
                    currentWeatherDataBean = gson.fromJson(buffer.toString(), CurrentWeatherDataBean.class);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (readers != null) {
                        try {
                            readers.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //处理更新
                    produce(currentWeatherDataBean);
                }
            }
            return null;
        }

        public void produce(CurrentWeatherDataBean currentWeatherDataBean) {
            if (currentWeatherDataBean != null) {
                //设置天气图标
                Calendar calendar = Calendar.getInstance();
                if (calendar.get(Calendar.HOUR_OF_DAY) > 18) {
                    //晚上
                    mRemoteViews.setImageViewResource(R.id.list_item_icon, Utility.convertIDtoWeatherICIcon(currentWeatherDataBean.getWeather().get(0).getId()));
                } else {
                    //白天
                    mRemoteViews.setImageViewResource(R.id.list_item_icon, Utility.convertIDtoWeatherArtIcon(currentWeatherDataBean.getWeather().get(0).getId()));
                }
                //气温
                StringBuffer buffer = new StringBuffer();
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
                String value = sharedPreferences.getString(WeatherPreferenceActivity.METRIC_KEY, "0");
                Boolean convert;
                if (value.equals("0")) {
                    convert = false;
                } else {
                    convert = true;
                }
                buffer.append(Utility.convertCelsiusToFahrenheit((int) (currentWeatherDataBean.getMain().getTemp()), convert));
                //气象描述
                buffer.append(Utility.convertIDtoDes(currentWeatherDataBean.getWeather().get(0).getId()));
                //设置气象描述
                mRemoteViews.setTextViewText(R.id.list_item_desc, buffer.toString());
                //设置时间
                mRemoteViews.setTextViewText(R.id.list_item_date_textview, Utility.convertTimeStampToDate(currentWeatherDataBean.getDt()));
            } else {
                //如果网络出现故障, 读取数据库缓存
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                String cityName = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "error");
                Cursor cursor = getApplication().getContentResolver().query(
                        WeatherContract.WEATHER_CONTENT_URI.buildUpon().appendPath("cityName").appendPath(cityName).build(),
                        null,
                        null,
                        null,
                        null
                );
                if (cursor != null && cursor.moveToFirst()) {
                    //设置天气图标
                    Calendar calendar = Calendar.getInstance();
                    if (calendar.get(Calendar.HOUR_OF_DAY) > 18) {
                        //晚上
                        mRemoteViews.setImageViewResource(R.id.list_item_icon, Utility.convertIDtoWeatherICIcon(cursor.getInt(cursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WEATHER))));
                    } else {
                        //白天
                        mRemoteViews.setImageViewResource(R.id.list_item_icon, Utility.convertIDtoWeatherArtIcon(cursor.getInt(cursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WEATHER))));
                    }
                    //气温
                    StringBuffer buffer = new StringBuffer();
                    String value = sharedPreferences.getString(WeatherPreferenceActivity.METRIC_KEY, "0");
                    Boolean convert;
                    if (value.equals("0")) {
                        convert = false;
                    } else {
                        convert = true;
                    }
                    buffer.append(Utility.convertCelsiusToFahrenheit(cursor.getInt(cursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_TEMP_MAX)), convert));
                    //气象描述
                    buffer.append(Utility.convertIDtoDes(cursor.getInt(cursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WEATHER))));
                    //设置气象描述
                    mRemoteViews.setTextViewText(R.id.list_item_desc, buffer.toString());
                    //设置时间
                    mRemoteViews.setTextViewText(R.id.list_item_date_textview, Utility.convertTimeStampToDate(cursor.getLong(cursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_TIME))));
                    cursor.close();
                }
            }
            //设置农历
            LunarCalendar lunarCalendar = new LunarCalendar();
            mRemoteViews.setTextViewText(R.id.list_item_lunar, lunarCalendar.toString());
            //为视图绑定监听器
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            PendingIntent startMainActivity = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            mRemoteViews.setOnClickPendingIntent(R.id.container, startMainActivity);
            //通知挂件管理器更新视图
            ComponentName thiswidget = new ComponentName(mContext, WeatherAppWidgetProvider.class);
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
            appWidgetManager.updateAppWidget(thiswidget, mRemoteViews);
        }

        public Cursor getDetailCityInfo() {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String cityName = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "");
            Cursor cursor = getApplicationContext().getContentResolver().query(
                    WeatherContract.LOCATION_CONTENT_URI,
                    null,
                    WeatherContract.LocationEntry.COLUMN_NAME + "= ?",
                    new String[]{cityName},
                    null);
            return cursor;
        }
    }
}
